package com.study.demo.aop.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: elvin
 * @time: 2019-10-09 17:20
 * @desc:
 **/
public class StudyCGLIBProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object target, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object res = null;
        if ("studyChinese".equals(method.getName())) {
            System.out.println(args[0] + "语文成绩很棒!");
            //执行目标方法
            res = proxy.invokeSuper(target, args);
            System.out.println("语文老师非常喜欢" + args[0] + ", 因为这次语文考的好; ");
        }
        else if("studyEnglish".equals(method.getName())) {
            System.out.println(args[0] + "英语成绩一般般");
            //执行目标方法
            res = proxy.invokeSuper(target, args);
            System.out.println("英语希望" + args[0] + "同学能够更加努力一点; ");
        }
        return res;
    }

    public Object createProxyObj(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        Object o = enhancer.create();
        return o;
    }
}
